﻿using AutoMapper;
using Microsoft.EntityFrameworkCore.Query.Internal;
using MyToDo.Content;
using MyToDo.Content.UnitOfWork;
using MyToDo.Dtos;
using MyToDo.Shared.Parameters;
using System.Collections.ObjectModel;
namespace MyToDo.Service
{
    public class ToDoService : IToDoService
    {
        private readonly IUnitOfWork work;
        private readonly IMapper mapper;

        public ToDoService(IUnitOfWork work,IMapper mapper)
        {
            this.work = work;
            this.mapper = mapper;
        }
        public async Task<ApiResponse> AddAsync(ToDoDto model)
        {
            try
            {
                var todo = mapper.Map<ToDo>(model);
                todo.CreatDate = DateTime.Now;
                await work.GetRepository<ToDo>().InsertAsync(todo);
                if (await work.SaveChangesAsync() > 0)
                    return new ApiResponse(true,todo);
                return new ApiResponse("添加数据失败");
            }
            catch (Exception ex)
            {

                return new ApiResponse(ex.Message);
            }
        }

        public async Task<ApiResponse> DeleteAsync(int id)
        {
            try
            {
                var repository=work.GetRepository<ToDo>();
                var todo = await repository
                    .GetFirstOrDefaultAsync(predicate: x => x.Id.Equals(id));
                repository.Delete(todo);
                if(await work.SaveChangesAsync()>0)
                    return new ApiResponse(true,"");
                return new ApiResponse("删除数据失败");
            }
            catch (Exception ex)
            {
                return new ApiResponse(ex.Message);
            }
        }

        public async Task<ApiResponse> GetAllAsync(QueryParameters parameters)
        {
            try
            {
                var repository = work.GetRepository<ToDo>();
                var todos = await repository.GetPagedListAsync(
                    predicate: x => string.IsNullOrWhiteSpace(parameters.Search) ? true : x.Title.Contains(parameters.Search),
                    pageIndex: parameters.PageIndex,
                    pageSize: parameters.PageSize,
                    orderBy: source => source.OrderByDescending(t => t.CreatDate));
                return new ApiResponse(true, todos);
            }
            catch (Exception ex)
            {
                return new ApiResponse(ex.Message);
            }
        }

        public async Task<ApiResponse> GetAllFilterAsync(ToDoParameter doParameter)
        {
            try
            {

                var repository = work.GetRepository<ToDo>();
                var todos = await repository.GetPagedListAsync(
                      predicate: x => (string.IsNullOrWhiteSpace(doParameter.Search) ? true : x.Title.Contains(doParameter.Search))
                      && (doParameter.Status == null ? true : x.Status.Equals(doParameter.Status)),
                      pageIndex: doParameter.PageIndex,
                      pageSize: doParameter.PageSize, orderBy: source => source.OrderByDescending(t => t.CreatDate)
                      );
                return new ApiResponse(true, todos);
            }
            catch (Exception ex)
            {
                return new ApiResponse(ex.Message);
            };
        }

        public async Task<ApiResponse> GetSingleAsync(int id)
        {
            try
            {
                var repository = work.GetRepository<ToDo>();
                var todo = await repository.GetFirstOrDefaultAsync(predicate:x=>x.Id.Equals(id));
                return new ApiResponse(true, todo);
            }
            catch (Exception ex)
            {
                return new ApiResponse(ex.Message);
             
            }
        }
        /// <summary>
        /// 查询代办事项的总数，完成效率等等
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResponse> Summary()
        {
            try
            {
                //代办事项按照时间排序结果
                var todos = await work.GetRepository<ToDo>().GetAllAsync(
                    orderBy: source => source.OrderByDescending(t => t.CreatDate));
                //备忘录按照时间顺序排序
                var memos = await work.GetRepository<Memo>().GetAllAsync(
                    orderBy: s => s.OrderByDescending(t => t.CreatDate));
                //状态栏中的信息
                SummaryDto summary = new SummaryDto();
                summary.Sum=todos.Count();
                summary.Todolist = new ObservableCollection<ToDoDto>(mapper.Map<List<ToDoDto>>(todos.Where(t=>t.Status==0)));//列表中只显示未完成的总数
                summary.Memolist = new ObservableCollection<MemoDto>(mapper.Map<List<MemoDto>>(memos));
                summary.MemoCount = memos.Count();
                summary.CompletedCount = todos.Where(t => t.Status == 1).Count();
                summary.CompletedRatio = (summary.CompletedCount / (double)summary.Sum).ToString("0%");

                return new ApiResponse(true,summary);
            }
            catch (Exception ex)
            {

               return new ApiResponse(ex.Message);
            }
        }

        public async Task<ApiResponse> UpdateAsync(ToDoDto model)
        {
            try
            {
                var tododto=mapper.Map<ToDo>(model);
                var repository = work.GetRepository<ToDo>();
                var todo = await repository.GetFirstOrDefaultAsync(predicate: x => x.Id.Equals(tododto.Id));
                todo.Title = tododto.Title;
                todo.Content = tododto.Content;
                todo.Status = tododto.Status;
                todo.UpdateDate = tododto.UpdateDate;
                repository.Update(todo);
                if (await work.SaveChangesAsync() > 0)
                    return new ApiResponse(true, todo);
                return new ApiResponse("更新数据异常。");

            }
            catch (Exception ex)
            {
                return new ApiResponse(ex.Message);
            }
        }
    }
}
